<?php

namespace app\controller;


use app\BaseController;
use app\common\TencentIm;
use app\model\Sms;
use app\model\Users;
use app\Request;
use app\tool\Http;
use think\db\exception\DbException;
use think\Exception;
use think\facade\Db;
use think\response\Json;

class PageController extends BaseController
{
	
	protected array $middleware = ['Login' => [
		'except' => ['build_users', 'login', 'sendSms'],
	]];
	protected $head_image = '/uploads/20231115/f57ebce8a72b823912904fe76eda0909.png';
	
	
	/**
	 * 批量生成用户
	 * @return void
	 */
	function build_users()
	{
		$TencentIm = TencentIm::getInstance();
		
		for ($i = 1; $i <= 50; $i++) {
			$rand = mt_rand(10000000, 99999999);
			do {
				$rand++;
			} while (Users::where(['invite_code' => $rand])->find());
			// 启动事务
			Db::startTrans();
			try {
				$ret = Users::create([
					'nickname' => '用户' . $rand,
					'mobile' => $rand,
					'head_image' => $this->head_image,
					'invite_code' => $rand,
					'logintime' => time()
				]);
				$ret = json_decode($TencentIm->account_import((string)$ret->id, $ret->nickname, config('app.static_host') . $ret->head_image));
				if ($ret->ErrorCode != 0) {
					throw new Exception($ret->ErrorInfo);
				}
				// 提交事务
				Db::commit();
			} catch (Exception $e) {
				// 回滚事务
				Db::rollback();
				writeJson(0, $e->getMessage());
			}
		}
		writeJson();
	}
	
	/**
	 * 登录
	 */
	function login(Request $request)
	{
		$mobile = $request->post('mobile');
		$captcha = $request->post('captcha');
		$logintype = $request->post('logintype');# 登录类型 mobile wechat_mini wechat qq
		$wechat_code = $request->post('wechat_code');
		$wechat_mini_code = $request->post('wechat_mini_code');
		$qq_code = $request->post('qq_code');
		
		
		$rand = rand(1000000, 9999999);
		do {
			$rand++;
		} while (Users::where(['invite_code' => $rand])->find());
		
		$head_image = $this->head_image;
		$nickname = "用户$rand";
		
		$unionid = '';
		$wechat_openid = '';
		$wechat_mini_openid = '';
		$qq_openid = '';
		switch ($logintype){
			case 'mobile':
				$ret = \app\common\Sms::check($mobile, $captcha, 'mobilelogin');
				if (!$ret && $captcha != '8520') {
					writeJson(0, '验证码不正确');
				}
				$users = Users::where(['mobile' => $mobile])->find();
				if (!empty($wechat_mini_code)){
					$res = Http::get('https://api.weixin.qq.com/sns/jscode2session', [
						'appid' => 'wxa79b2797e3e71208',
						'secret' => '0fceef56da1ad3ef55f9be78ece5c9cd',
						'js_code' => $wechat_mini_code,
						'grant_type' => 'authorization_code'
					]);
					$res = json_decode($res);
					if (empty($res->unionid)) {
						writeJson(0, $res->errmsg);
					}
					$wechat_mini_openid = $res->openid;
					$unionid = $res->unionid;
				}
				break;
			case 'wechat':
				$res = Http::get('https://api.weixin.qq.com/sns/oauth2/access_token', [
					'appid' => 'wx986505053e901dff',
					'secret' => '2e149d801f4f03aa528045c39bc39254',
					'code' => $wechat_code,
					'grant_type' => 'authorization_code'
				]);
				$res = json_decode($res);
				if (empty($res->unionid)) {
					writeJson(0, $res->errmsg);
				}
				$wechat_openid = $res->openid;
				$unionid = $res->unionid;
				$users = Users::where('unionid', $unionid)->find();
				break;
			case 'wechat_mini':
				$res = Http::get('https://api.weixin.qq.com/sns/jscode2session', [
					'appid' => 'wxa79b2797e3e71208',
					'secret' => '0fceef56da1ad3ef55f9be78ece5c9cd',
					'js_code' => $wechat_mini_code,
					'grant_type' => 'authorization_code'
				]);
				$res = json_decode($res);
				if (empty($res->unionid)) {
					writeJson(0, $res->errmsg);
				}
				$wechat_mini_openid = $res->openid;
				$unionid = $res->unionid;
				$users = Users::where('unionid', $unionid)->find();
				break;
			case 'qq':
				$users = Users::where('qq_openid', $qq_code)->find();
				$qq_openid = $qq_code;
				break;
			default:
				writeJson(0,'登陆方式错误');
			
		}
		if ($users) {
			if (!empty($wechat_mini_openid)){
				$users->wechat_mini_openid = $wechat_mini_openid;
			}
			if (!empty($wechat_openid)){
				$users->wechat_openid = $wechat_openid;
			}
			if (!empty($unionid)){
				$users->unionid = $unionid;
			}
			if (!empty($qq_openid)){
				$users->qq_openid = $qq_openid;
			}
			$users->login_time = time();
			$users->save();
		} else {
			//注册
			$users = Users::create([
				'nickname' => $nickname,
				'mobile' => $mobile,
				'head_image' => $head_image,
				'invite_code' => $rand,
				'logintime' => time(),
				'wechat_openid' => $wechat_openid,
				'wechat_mini_openid' => $wechat_mini_openid,
				'unionid' => $unionid,
				'qq_openid' => $qq_openid,
			]);
			$TencentIm = TencentIm::getInstance();
			$ret = json_decode($TencentIm->account_import($users->id, "用户$rand", config('app.static_host') . $this->head_image));
			if ($ret->ErrorCode != 0) {
				writeJson(0, $ret->ErrorInfo);
			}
		}
		$token = ['users_id' => $users->id];
		writeJson(['token' => sign_token($token)]);
	}
	
	/**
	 * 发送验证码
	 * event 验证码类型:登录=mobilelogin,注册=register,换绑手机号=changemobile,更改密码=changepwd,重置密码=resetpwd
	 * @param Request $request
	 * @return Json
	 * @throws DbException
	 */
	function sendSms(Request $request)
	{
		$params = $request->param();
		$event = $params['event'] ?? 'register';
		
		try {
			validate(\app\validate\Sms::class)->check($params);
		} catch (\Exception $e) {
			writeJson(0, $e->getMessage());
		}
		$ipSendTotal = Sms::where(['ip' => $request->ip()])->whereTime('createtime', '-1 hours')->count();
		$last = Sms::where(['mobile' => $params['mobile'], 'event' => $event])->order('id', 'DESC')->find();
		if (($last && time() - $last->getData('createtime') < 60) || $ipSendTotal >= 10) {
			writeJson(0, '发送频繁');
		}
		if ($event) {
			$userinfo = Users::getByMobile($params['mobile']);
			if ($event == 'register' && $userinfo) {
				//已被注册
				writeJson(0, '已被注册');
			} elseif ($event == 'changemobile' && $userinfo) {
				//被占用
				writeJson(0, '已被占用');
			} elseif (in_array($event, ['changepwd', 'resetpwd']) && !$userinfo) {
				//未注册
				writeJson(0, '未注册');
				
			}
		}
	
		$ret = \app\common\Sms::send($params['code'],$params['mobile'], null, $event);
		if ($ret) {
			writeJson();
		} else {
			writeJson(0, '发送失败');
		}
	}
	
	
}